<template>
    <div class="app-container tz-app continuous-box">


        <div class="radio-query">
            <div class="flex-left flex">
                <el-input class="zt-input rihgt-m5" v-model="queryParams.regionalNodeName" placeholder="方案名称"
                    style="width: 260px;" />
                <el-date-picker class="zt-input-min rihgt-m5" style="width: 145px;" v-model="queryParams.updateTime"
                    type="date" placeholder="选择日期">
                </el-date-picker>
                <el-select v-model="queryParams.isUsed" filterable placeholder="状态" class="zt-input-min"
                    style="margin-right: 15px;">

                    <el-option label="启用" value="1"></el-option>
                    <el-option label="停用" value="0"></el-option>
                </el-select>
                <button class="bt-blue " @click="handleQuery">查询</button>

            </div>
            <button class="bt-yellow " @click="handleAdd">新增</button>
        </div>
        <div class="flex">
            <div class="tz-table-box no-bg-talbe"
                :class="{ 'continuous-box-left-yes': detailData, 'continuous-box-left-no': !detailData }"
                style="padding-right: 0;">
                <el-table :data="continuousList" @selection-change="handleSelectionChange" :row-class-name="getRowClassName"
                    @row-click="handleRowClick" style="padding-top: 20px;" height="calc(100vh - 245px)" class="zt-table">
                    <!-- <el-table-column label="方案ID" align="center" prop="detectionSchemeId" /> -->
                    <el-table-column label="方案名称" align="center" prop="detectionSchemeName" />
                    <el-table-column label="最近启动时间" align="center" prop="createTime" />
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="400">
                        <template slot-scope="scope">
                            <!-- <el-button size="mini" type="text" icon="el-icon-edit"
                                v-hasPermi="['system:node:edit']">修改</el-button>
                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                                v-hasPermi="['system:node:remove']">删除</el-button> -->
                            <div class="flex-s continuous-button">
                                <div class="start-button"><img src="@/assets/img/st2.png">启动探测</div>
                                <!-- <div class="proceed-button"><img src="@/assets/img/st1.png">探测中...</div> -->
                                <div class="examine-button"><img src="@/assets/img/de3.png">结果检测</div>
                                <!-- <div class="examine-button"><img src="@/assets/img/de2.png">结果检测</div> -->
                                <div class="station-button"><img src="@/assets/img/de1.png">电台状态</div>
                                <!-- <img class="delete-button" src="@/assets/img/delete-bin1.png"> -->
                                <img class="delete-button" src="@/assets/img/delete-bin2.png"
                                    @click="handleDelete(scope.row)">
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" style="margin-right: 50px;" @pagination="getList" />

            </div>
            <!-- <div class="continuous-detail" v-if="detailData"> -->
            <div class="continuous-detail" v-if="true">
                <div class="flex-item li-detail">
                    <div class="detail-text">方案名称:</div><el-input class="blue-input"
                        v-model="detailData.detectionSchemeName" placeholder="方案名称" style="width: 90%;" />
                </div>
                <div class="flex-item li-detail">

                    <div class="detail-text">禁用频率:</div>

                    <el-select v-model="detailData.forbidFrequency" multiple filterable placeholder="频率"
                        class="z-input-multiple" style="width: 400px;font-weight: 600;">
                        <el-option v-for="item in  dict.type.forbid_frequency" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>

                    <el-upload class="upload-demo" :action="upload.url" :show-file-list="false" :headers="upload.headers"
                        :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess2" name="file">
                        <div class="excl "><img src="@/assets/img/ex.png">上传excl</div>
                    </el-upload>
                    <button class="bt-blue" @click="submitUp">保存</button>

                </div>
                <div class="li-detail">
                    <el-table :data="detailData.pltChooseDetectionTimeList" height="calc(100vh - 435px)"
                        @row-click="handleTimeClick" class="zt-min-table">
                        <el-table-column label="时段" align="center">
                            <template slot-scope="scope" width="140">
                                <div>{{ scope.row.timeStart }}-{{ scope.row.timeEnd }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="选取频率" show-overflow-tooltip align="center">
                            <template slot-scope="scope" width="140">
                                {{ scope.row.frequencieString }}
                            </template>
                        </el-table-column>
                        <el-table-column label="功率" align="center" prop="efficiency" />
                        <el-table-column label="服务电台" align="center" prop="radioStation" width="220"
                            show-overflow-tooltip />
                    </el-table>
                </div>
            </div>

        </div>
        <right-dialog :title="title" :visible="open" @closeDialog="cancel">
            <template v-slot:default>
                <div class="zt-dialog-solt">
                    <div class="continuous-detail" v-if="true"
                        style="height: 100%;margin: 0; padding: 0 20px;background-color: rgb(0, 0, 0,0);">
                        <div class="flex-item li-detail">
                            <div class="detail-text">方案名称:</div><el-input class="blue-input"
                                v-model="form.detectionSchemeName" placeholder="方案名称" style="width: 90%;" />
                        </div>
                        <div class="flex-item li-detail">

                            <div class="detail-text">禁用频率:</div>

                            <el-select v-model="form.forbidFrequency" multiple filterable placeholder="频率"
                                class="z-input-multiple" style="width: 400px;font-weight: 600;">
                                <el-option v-for="item in  dict.type.forbid_frequency" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>

                            <el-upload class="upload-demo" :action="upload.url" :show-file-list="false"
                                :headers="upload.headers" :before-upload="handleBeforeUpload"
                                :on-success="handleUploadSuccess" name="file">
                                <div class="excl "><img src="@/assets/img/ex.png">上传excl</div>
                            </el-upload>
                            <button class="bt-blue" @click="submitForm">保存</button>

                        </div>
                        <div class="li-detail">
                            <el-table :data="form.pltChooseDetectionTimeList" height="calc(100vh - 435px)"
                                @row-click="handleTimeClick" class="zt-min-table">
                                <el-table-column label="时段" align="center">
                                    <template slot-scope="scope" width="140">
                                        <div>{{ scope.row.timeStart }}-{{ scope.row.timeEnd }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="选取频率" align="center" show-overflow-tooltip>
                                    <template slot-scope="scope" width="140">
                                        {{ scope.row.frequencieString }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="功率" align="center" prop="efficiency" />
                                <el-table-column label="服务电台" align="center" prop="radioStation" width="220"
                                    show-overflow-tooltip />
                            </el-table>
                        </div>
                    </div>

                </div>

            </template>
        </right-dialog>

        <right-dialog :title="timeData.title" width="400px" :visible="timeData.open" @closeDialog="cancelTime">
            <template v-slot:default>
                <div style="margin-top: 30px;">
                    <el-form ref="form" :model="timeData.data" label-width="120px">
                        <el-form-item label="时段:">
                            <div style="color: #fff;">
                                {{ timeData.data.timeStart }}-{{ timeData.data.timeEnd }}
                            </div>
                        </el-form-item>
                        <el-form-item label="选取频率:">
                            <t-input :arr="timeData.frequencies" @getArr="getFrequencies" style="width: 590px;"></t-input>
                        </el-form-item>
                    </el-form>
                    <button class="bt-blue button-time" @click="timeSubmit">保存</button>
                </div>
            </template>
        </right-dialog>



    </div>
</template>
  
<script>
// import { listNode, getNode, delNode, addNode, updateNode } from "@/api/business/node";
import { addChooseScheme, listChooseScheme, getChooseScheme, updatChooseScheme, delChooseScheme } from "@/api/business/selecting";

import RightDialog from "@/components/TZ/RightDialog"
import MinDialog from "@/components/TZ/MinDialog"
import NodeUl from "@/components/TZ/NodeUl"
import Crate from "@/components/TZ/Crate"
import { getToken } from "@/utils/auth";
import TInput from "@/components/TZ/TInput"
import Decimal from 'decimal.js';


export default {
    name: "Node",
    components: { RightDialog, NodeUl, Crate, MinDialog, TInput },
    dicts: ['located_address', 'forbid_frequency'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 台站表格数据
            continuousList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                regionalNodeName: null,
                regionalNodeType: null,
                locatedAddress: null,
                updateTime: null,
                status: null,
                contacts: null,
                isUsed: null,
            },
            // 表单参数
            form: {},
            beforeForm: {},
            // 表单校验
            rules: {

            },
            detailData: null,
            detailList: {
                antenna: [],
                camera: [],
                machineRoom: [],
                sensor: [],
            },
            detailPerPage: 8,
            selectedRow: null,
            upload: {
                url: process.env.VUE_APP_BASE_API + '/business/chooseTime/importData',  // 上传的文件服务器地址
                headers: {
                    "Authorization": "Bearer " + getToken(),
                },
            },
            timeData: {
                data: null,
                title: '24小时任务列表编辑',
                open: false,
                frequencies: [],
                time: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 8, 40)],

            },
        };
    },
    created() {
        this.reset();
        this.resetTime();
        this.getList();
    },
    computed: {

    },
    methods: {
        //上传文件
        // 上传前校检w文件
        handleBeforeUpload(file) {
            const type = ["text/csv"];
            const isJPG = type.includes(file.type);
            // // 检验文件格式
            if (!isJPG) {
                this.$message.error(`请上传csv文件!`);
                return false;
            }
            // 校检文件大小
            // if (this.fileSize) {
            //     const isLt = file.size / 1024 / 1024 < this.fileSize;
            //     if (!isLt) {
            //         this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
            //         return false;
            //     }
            // }
        },
        //上传成功
        handleUploadSuccess(res, file) {
            if (res.code == 200) {
                this.$message({
                    showClose: true,
                    message: '上传成功',
                    type: 'success'
                });
                this.form.pltChooseDetectionTimeList = res.rows
                this.form.pltChooseDetectionTimeList.forEach((item, index) => {
                    const arr = this.combinedArray(item).join(', ')
                    this.$set(item, 'frequencieString', arr);
                });

            }
        },
        handleUploadSuccess2(res, file) {
            if (res.code == 200) {
                this.$message({
                    showClose: true,
                    message: '上传成功',
                    type: 'success'
                });
                // this.form.pltChooseDetectionTimeList = res.rows
                this.detailData.pltChooseDetectionTimeList = res.rows
                this.detailData.pltChooseDetectionTimeList.forEach((item, index) => {
                    // 使用 Vue.set 添加 num 属性
                    const arr = this.combinedArray(item).join(', ')
                    this.$set(item, 'frequencieString',arr);
                });

            }
        },
        getRowClassName({ row }) {
            if (this.detailData != null) {
                return row.detectionSchemeId == this.detailData.detectionSchemeId ? 'click-node' : '';
            }
            return ''
        },

        /** 查询台站列表 */
        getList() {
            this.loading = true;
            listChooseScheme(this.queryParams).then(response => {
                this.continuousList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },

        resetIds() {

        },
        // 表单重置
        reset() {
            this.form = {
                detectionSchemeName: null,
                detectionSchemeId: null,
                forbidFrequency: null,
                regionalNodeId: null,
                pltChooseDetectionTimeList: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
            };
            this.resetForm("form");
            this.detailData = {
                detectionSchemeName: null,
                detectionSchemeId: null,
                forbidFrequency: null,
                regionalNodeId: null,
                pltChooseDetectionTimeList: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
            }
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.regionalNodeId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加方案";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const regionalNodeId = row.regionalNodeId || this.ids
            // getNode(regionalNodeId).then(response => {
            //     this.form = response.data;
            //     this.open = true;
            //     this.title = "修改台站";
            //     this.getListAll(this.form.locatedAddress);
            // });
        },
        /** 提交按钮 */
        submitForm() {
            this.form.forbidFrequency = this.form.forbidFrequency.join(', ')
            if (this.form.detectionSchemeId != null) {
            } else {
                addChooseScheme(this.form).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                    this.reset()
                });
            }
        },
        submitUp() {
            this.detailData.forbidFrequency = this.detailData.forbidFrequency.join(', ')
            updatChooseScheme(this.detailData).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const detectionSchemeId = row.detectionSchemeId;
            this.$modal.confirm('是否确认删除台站编号为"' + detectionSchemeId + '"的数据项？').then(function () {
                return delChooseScheme(detectionSchemeId);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/node/export', {
                ...this.queryParams
            }, `node_${new Date().getTime()}.xlsx`)
        },
        handleRowClick(row) {//点击查询详细
            const detectionSchemeId = row.detectionSchemeId
            getChooseScheme(detectionSchemeId).then(response => {
                this.detailData = response.data;
                this.detailData.pltChooseDetectionTimeList.forEach((item, index) => {
                    const arr = this.combinedArray(item).join(', ')
                    this.$set(item, 'frequencieString', arr);
                });
                this.detailData.forbidFrequency = this.stringToArray(this.detailData.forbidFrequency);
            });
        },
        stringToArray(str) {
            if (!str) {
                return [];
            }
            if (str.includes(',')) {
                return str.split(', ');
            }
            return [str];
        },
        // 使用计算属性来合成数字数组
        combinedArray(row) {
            let frequencies = [];
            // 循环遍历frequency属性
            for (let i = 1; i <= 10; i++) {
                const key = `frequency${i.toString().padStart(2, '0')}`;
                const value = row[key];
                // console.log(value + "-" + new Decimal(value).mul(0.0000001).toNumber());
                // 将字符串转换为数字并添加到数组
                // 不为null才能添加
                if (row[key] != null) {
                    frequencies.push(new Decimal(value).mul(0.0000001).toNumber());
                }
            }
            return frequencies;
        },
        setFrequencies(row) {
            // 确保数组的长度不超过10
            const maxLength = Math.min(row.length, 10);
            // 这里获取到修改的值，要改变this.timeData.data
            // 将数组值分配给frequency属性
            for (let i = 1; i <= 10; i++) {
                let key = `frequency${i.toString().padStart(2, '0')}`;
                if (i <= maxLength) {
                    // 获取要赋给属性的值
                    let value = row[i - 1];
                    value = new Decimal(value).mul(10000000).toNumber();
                    this.$set(this.timeData.data, key, value);
                } else {
                    // 如果超过了 maxLength，将属性设置为 null
                    this.$set(this.timeData.data, key, null);
                }
            }
        },
        getFrequencies(arr) {
            this.setFrequencies(arr);
        },
        resetTime() {
            this.timeData.data = {
                detectionSchemeId: null,
                detectionTimeId: null,
                efficiency: null,
                frequencyEnd: null,
                frequencyStart: null,
                radioStation: null,
                remark: null,
                timeEnd: null,
                timeStart: null,
            }
        },
        handleTimeClick(row) {//查看时段详细
            this.timeData.data = Object.assign({}, row);
            const arr = this.combinedArray(row);
            this.timeData.frequencies = arr
            this.timeData.open = true
        },
        cancelTime() {
            this.timeData.open = false
            this.resetTime();//清空timeData.data数据
            this.timeData.time = null
            this.timeData.frequencies = []
           
        },
        timeSubmit() {
            // getFrequencies(arr);
            this.updateDetectionTime(this.timeData.data);//保存数据
              this.detailData.pltChooseDetectionTimeList.forEach((item, index) => {
                const arr = this.combinedArray(item).join(', ')
                this.$set(item, 'frequencieString', arr);
            });
            this.cancelTime();//关闭弹窗重置数据
        },
        updateDetectionTime(updatedData) {

            // 遍历 this.detailData.pltChooseDetectionTimeList 数组
            this.detailData.pltChooseDetectionTimeList = this.detailData.pltChooseDetectionTimeList.map(item => {
                // 检查 detectionTimeId 是否与 this.timeData.data 中的某个元素相等
                if (item.detectionTimeId === updatedData.detectionTimeId) {
                    // 如果相等，使用 updatedData 更新当前元素
                    return updatedData;
                } else {
                    // 如果不相等，保持元素不变
                    return item;
                }
            });

            // 现在，this.detailData.pltChooseDetectionTimeList 中具有相同 detectionTimeId 的元素已经被更新

        },



    }
};
</script>
  

<style rel="stylesheet/scss" lang="scss" scoped>
.continuous-box-left-yes {
    width: calc(100% - 800px);
}

.continuous-box-left-no {
    width: 100%;
}

.tz-table-box {
    background: none;
    height: calc(100vh - 150px);
}

.continuous-button {
    width: 100%;
    font-size: 14px;

    .start-button,
    .proceed-button {
        width: 100px;
        display: flex;
        align-items: center;
        border-radius: 30px;
        color: #EFEFEF;
        padding: 2px 10px;
        text-align: center;
        cursor: pointer;

        img {
            width: 10px;

        }

        margin-right: 10px;
    }

    .start-button {
        background-color: #036EB7;
        border: solid 1px #74C8CE;

        img {
            margin-right: 8px;
            margin-left: 2px;
        }
    }

    .proceed-button {
        background-color: #FABD68;
        border: solid 1px #FBD580;

        img {
            margin-right: 10px;
            margin-left: 2px;
        }
    }

    .examine-button,
    .station-button {
        cursor: pointer;
        display: flex;
        align-items: center;

        // line-height: 14px;
        img {
            width: 20px;
            margin-right: 2px;
        }

        margin-right: 5px;
    }

    .delete-button {
        width: 25px;
        height: 25px;
    }
}

.upload-demo {
    margin-right: 10px;
    margin-left: 10px;
}

.continuous-box {
    .min-dialog {
        height: 400px;
        padding-top: 30px;

        .bt-blue {
            margin-top: 120px;
            margin-left: 250px;
        }

        .min-dialog-li {
            display: flex;
            // align-items: center;
            align-content: center;
            width: 400px;
            padding: 10px 20px;
        }

        .headline-text {
            width: 70px;
            margin-right: 10px;
            text-align: right;
            color: #9A9DAA;
            font-size: 14px;
            margin-left: auto;
        }
    }
}

.button-time {
    position: absolute;
    bottom: 40px;
    right: 40px;
}
</style>